package generator 
{
	import Components.CauseDamage;
	import nl.jorisdormans.phantom2D.objects.GameObject;
	/**
	 * ...
	 * @author Joris Dormans
	 */
	public class PlatformGenerator extends Generator
	{	
		public function PlatformGenerator() 
		{
		}
		
		override public function generateRandomTiles(... types):void {
			trace("Generating random tiles...");
			
			if (types.length < 2) {
				throw new Error("PlatformGenerator.generateRandomTiles needs at least two different types of tiles");
			}
			
			for (var y:int = 2; y < tiledObjectLayer.tilesY; y++) {
				for (var x:int = 0; x < tiledObjectLayer.tilesX; x++) {
					var cell:Cell = getCellAt(x, y);
					if (cell) {
						var f:Number = (y - 2) / tiledObjectLayer.tilesY;
						f = f * f;
						
						
						if (Math.random() < f || y == tiledObjectLayer.tilesY-1) {
							var r:int = Math.random()*(types.length-1)+1; 
							cell.type = types[r];
						} else {
							cell.type = types[0];
						}

					}
				}
			}
		}
		
		
		override public function iterate():void 
		{
			trace("iterating...");
			super.doIteration(doCave);
		}
		
		private function doCave(cell:Cell):void  {
			var n:int = cell.countNeighbors(0, true);
			if (cell.type == 0) n++;
			if (n == 4 && Math.random()<0.1) cell.nextType = 0;
			if (n >= 5) cell.nextType = 0;
			else cell.nextType = 1;
			
			if (cell.type == 7) {
				cell.nextType = 7;
			} else {
				n = cell.countNeighbors(7, true);
				if (Math.random()*2<n) cell.nextType = 1;
				
				if (Cell.cellOnTile(cell.tile.up, 7) && Math.random()<0.6) {
					cell.nextType = 7;
				}
			}
		}
		
		public function createCorners():void {
			trace("creating corners...");
			doIteration(removeCores);
			trace("removing cores...");
			doIteration(doCorner);
			//this.drawTile = 6;
		}
		
		private function removeCores(cell:Cell):void  {
			if (cell.type == 7) cell.nextType = 1;
		}

		
		private function doCorner(cell:Cell):void  {
			if (cell.type != 1) return;
			var up:Boolean = Cell.cellOnTile(cell.tile.up, 1);
			var down:Boolean = Cell.cellOnTile(cell.tile.down, 1);
			var left:Boolean = Cell.cellOnTile(cell.tile.left, 1);
			var right:Boolean = Cell.cellOnTile(cell.tile.right, 1);
			
			if (!up && !right && down && left) cell.nextType = 2;
			if (up && !right && !down && left) cell.nextType = 3;
			if (up && right && !down && !left) cell.nextType = 4;
			if (!up && right && down && !left) cell.nextType = 5;
		}	
		
	}
	
}